package com.test.platform.dao;

import com.test.platform.model.Project;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface ProjectMapper {
    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM project p, (SELECT @rownum := 0) r " +
            "ORDER BY p.id DESC")
    List<Project> findAll();

    @Update("UPDATE project SET owner = #{owner}, name = #{name}, " +
            "description = #{description}, git_url = #{gitUrl} WHERE id = #{id}")
    int update(Project project);

    @Insert("INSERT INTO project (owner, name, description, git_url) " +
            "VALUES (#{owner}, #{name}, #{description}, #{gitUrl})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Project project);

    @Delete("DELETE FROM project WHERE id = #{id}")
    int deleteById(Integer id);

    @Delete("DELETE FROM project WHERE owner = #{owner} AND name = #{name}")
    int deleteByOwnerAndName(@Param("owner") String owner, @Param("name") String name);

    @Delete("DELETE FROM project")
    int deleteAll();

    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM project p, (SELECT @rownum := 0) r " +
            "WHERE p.id = #{id}")
    Project findById(Integer id);

    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM project p, (SELECT @rownum := 0) r " +
            "WHERE p.owner LIKE CONCAT('%', #{owner}, '%') " +
            "ORDER BY p.id DESC")
    List<Project> findByOwner(@Param("owner") String owner);

    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM project p, (SELECT @rownum := 0) r " +
            "WHERE p.name LIKE CONCAT('%', #{name}, '%') " +
            "ORDER BY p.id DESC")
    List<Project> findByName(@Param("name") String name);

    // 修改现有的方法为模糊查询
    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM project p, (SELECT @rownum := 0) r " +
            "WHERE p.owner LIKE CONCAT('%', #{owner}, '%') " +
            "AND p.name LIKE CONCAT('%', #{name}, '%') " +
            "ORDER BY p.id DESC")
    List<Project> findByOwnerAndName(@Param("owner") String owner, @Param("name") String name);
    
    @Update("UPDATE project SET description = #{description}, git_url = #{gitUrl} " +
            "WHERE owner = #{owner} AND name = #{name}")
    int updateProjectInfo(Project project);

    @Delete("<script>" +
            "DELETE FROM project WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int deleteByIds(@Param("ids") List<Integer> ids);
}